package cloud.xiangyixiang.www.spring.boot.java.basics.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * <p>
 * 多线程下载文件
 * </p>
 *
 * @author weixin
 * @date 2023/9/4 17:33
 */
public class MyDownloadRunnable implements Runnable {

    /**
     * 根路径
     */
    private static final String ROOT_PATH = System.getProperty("user.dir") + "/spring-boot-java-basics/src/main/resources/";

    private Socket socket;

    public MyDownloadRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        System.out.println("与客户端连接成功");

        try{
            //服务端向客户端发送消息
            OutputStream out = socket.getOutputStream();
            File file = new File(ROOT_PATH + "jquery-3.7.1.min.js");
            //将此文件从硬盘读到内存中
            InputStream in = new FileInputStream(file);
            //定义每次发送的文件大小
            byte[] bytes = new byte[1000];
            int len = -1;
            while ((len = in.read(bytes)) != -1){
                out.write(bytes,0,len);
            }
            in.close();
            out.close();
            socket.close();
        } catch (Exception e){
            System.out.println(e);
        }
    }

}
